﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace ViewMaker.Core.Wpf
{
    public static class SelectionChangedBehavior
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(SelectionChangedBehavior), new PropertyMetadata(CommandCallback));

        public static ICommand GetCommand(Selector obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(Selector obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        private static void CommandCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var ele = obj as Selector;
            if (ele != null)
            {
                ICommand cmd = (ICommand)args.NewValue;

                if (args.OldValue == null && args.NewValue != null)
                {
                    ele.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(SelectionChangedHandler);
                }
                else if (args.OldValue != null && args.NewValue == null)
                {
                    ele.SelectionChanged -= new System.Windows.Controls.SelectionChangedEventHandler(SelectionChangedHandler);
                }
            }
        }

        static void SelectionChangedHandler(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var ele = e.OriginalSource as Selector;
            ICommand cmd = (ICommand)ele.GetValue(CommandProperty);
            if (cmd != null) cmd.Execute(e.AddedItems);
        }

    }

}
